clear
set more off

cap prog drop inner
prog define inner
syntax, yvar(string)

    cap log close
    log using $logdir/distributions_`yvar'.log, replace

    use firm_id ertc ertc_amendment tp wg_amt govt using $fromsasdir/result if tp < 202112 & ertc + ertc_amendment > 0, clear
	drop if ertc > 900*10^6
    qui replace ertc = ertc + ertc_amendment
    qui gen post = tp >= 202103
    gcollapse govt (sum)  ertc, by(firm_id post) fast
	gen year = 2020 + post

    *************************************
    *
    *      Step 1: Merge, if necessary 
    *
    **************************************
    if "`yvar'" == "owner_incm" {
		
        merge m:1 firm_id year using $fromsasdir/owner_incm, keep(1 3)
        keep if _merge == 3
        drop _merge
        drop if missing(mean_incm)
		drop if govt == 1
    }
    
    if "`yvar'" == "empl_even" {
        
        merge m:1 firm_id year using $fromsasdir/empl_even_wgt, keep(1 3)
        keep if _merge == 3
        drop _merge
    }
    if "`yvar'" == "empl_capped" {
        merge m:1 firm_id year using $fromsasdir/empl_capped_wgt, keep(1 3)
        keep if _merge == 3
        drop _merge
    }
     if "`yvar'" == "empl_wg" {
        merge m:1 firm_id year using $fromsasdir/empl_wg_wgt, keep(1 3)
        keep if _merge == 3
        drop _merge
    }   
    
    
    ******************************************
    *
    *           Step 2: Collapse
    *
    ******************************************
    local dlist dneg d0 d10 d25 d50 d100 d250 d1000
    
    foreach k in neg 0 10 25 50 100 250 1000 {
    
        tempvar any wgt
    
        gen `any' = d`k' > 0
        assert r(sum) >= 5
        
        qui gen `wgt' = ertc*d`k'
        qui sum `wgt'
        assert r(max) <= 0.4*r(sum)
        
    }
    
   gcollapse `dlist' [aw=ertc], fast

    list

    qui save $outdir/distributions_`yvar', replace

cap log close

end



inner, yvar(owner_incm)

inner, yvar(empl_even)
inner, yvar(empl_wg)
inner, yvar(empl_capped)


